package com.zjcode.cdcer.controller;

import com.alibaba.fastjson.JSONObject;
import com.chinatechstar.component.commons.controller.BaseController;
import com.chinatechstar.component.commons.result.ListResult;
import com.chinatechstar.component.commons.result.ResultBuilder;
import com.chinatechstar.component.commons.supports.PageData;
import com.chinatechstar.component.commons.utils.UuidUtil;
import com.zjcode.cdcer.model.*;
import com.zjcode.cdcer.model.basic.JsonObj;
import com.zjcode.cdcer.service.*;
import com.zjcode.cdcer.service.impl.SequenceService;
import com.zjcode.cdcer.utils.Utils;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 *  内镜、病理 数据 控制它
 */
@RestController
@Slf4j
@RequestMapping("/v1/cerSysteminitImportInfo/")
public class CerSysteminitImportInfoController extends BaseController {

    @Autowired
    private CerSysteminitImportInfoService cerSysteminitImportInfoService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private TkmSysUserService tkmSysUserService;
    @Autowired
    private CerPersonInfoService personInfoService;

    @Autowired
    private TkmSysteminitImportInfoService systeminitImportInfoService;
    @Autowired
    private SequenceService sequenceService;
    @Autowired
    private DataPushNationService dataPushNationService;

    @PostMapping("listAllTableData")
    @ApiOperation("获取所有的初始数据信息列表")
    public ListResult<Object> listAllTableData(@RequestBody PageData pageData) {
        return ResultBuilder.buildListSuccess(cerSysteminitImportInfoService.listAllTableData(pageData));
    }

    @PostMapping("addData")
    @ApiOperation("初始数据上报添加")
    public JsonObj addData() {
        //对数据进行json转换
        PageData pageData=this.getPageData();
        String json = JSONObject.toJSONString(pageData);
        CerInitData info = JSONObject.parseObject(json, CerInitData.class);
//        String user = (String) pageData.get(MConsts.Common.USER);
//        String tmp = (String) pageData.get(MConsts.Common.SKIP);
        // 放入用户机构数据
        if (StringUtils.isNotEmpty(info.getName())
                && StringUtils.isNotEmpty(info.getIdCard())
                && StringUtils.isNotEmpty(info.getProvinceName())
                && StringUtils.isNotEmpty(info.getDistrictName())
                && StringUtils.isNotEmpty(info.getCityName())
                && StringUtils.isNotEmpty(info.getCountyName())
                && StringUtils.isNotEmpty(info.getVillageName())
                && StringUtils.isNotEmpty(info.getSex())
                && StringUtils.isNotEmpty(info.getVillageId())
                && StringUtils.isNotEmpty(info.getNationCode())
                && StringUtils.isNotEmpty(info.getPhone())
                && StringUtils.isNotEmpty(info.getBirthday())
        ){
            // 获取extFlag
            String userId = (String)pageData.get("userId");
            String extFlag = sysUserService.findUserExtFlag(userId);
            // 获取用户的省市县区机构的编码与名称
            TkmUserOrgAndRegions regionsAndOrg = tkmSysUserService.findUserRegionsAndOrg(userId);
            SysOrg userOrg = regionsAndOrg.getSysOrg();
//            List<ZjcodeSysRegion> userRegions = regionsAndOrg.getRegions();
            String orgId = userOrg
                    .getId()
                    .toString();
            //判断有没有关联基础人员信息
            TkmSysteminitImportInfo tkmSysteminitImportInfo = getTkmSysteminitImportInfo(info);
            tkmSysteminitImportInfo.setInstitutionId(orgId);
            tkmSysteminitImportInfo.setInstitutionName(userOrg.getOrgName());
            tkmSysteminitImportInfo.setId(UuidUtil.get32UUID());
            tkmSysteminitImportInfo.setCreateBy(userId);
            tkmSysteminitImportInfo.setExtFlag(extFlag);
            tkmSysteminitImportInfo.setDeleted(0);
            tkmSysteminitImportInfo.setVersion(1);
            //默认食管，贲门,胃和治疗，随访数据为空
            tkmSysteminitImportInfo.setExtFlag2("0|0|0");
            tkmSysteminitImportInfo.setInsertDatetime(new Date(System.currentTimeMillis()));
            tkmSysteminitImportInfo.setLastUpdateDatetime(new Date(System.currentTimeMillis()));
            //对初始数据进行校验
            List<String> errors = Utils.validateSysteminitImportInfoData(tkmSysteminitImportInfo);
            if (errors.size() > 0) {
                tkmSysteminitImportInfo.setIsHaveError(1);
                tkmSysteminitImportInfo.setErrorMessage(errors
                        .stream()
                        .collect(Collectors.joining("|")));
            } else {
                tkmSysteminitImportInfo.setIsHaveError(0);
                tkmSysteminitImportInfo.setErrorMessage("");
            }
            //判断是否存在基础人员信息
            if (StringUtils.isEmpty(info.getPersonId())){
                //添加基础人员信息
                CerPersonalInfo cerPersonalInfo = getCerPersonalInfo(info);

                cerPersonalInfo.setInstitutionId(orgId);
                cerPersonalInfo.setInstitutionName(userOrg.getOrgName());
                cerPersonalInfo.setExtFlag(extFlag);
                cerPersonalInfo.setCreateBy(userId);
                //获取人员系统唯一标识
                String sequenceNumByCode = sequenceService.getSequenceByCode(cerPersonalInfo.getVillageId());
                cerPersonalInfo.setScreeningId(sequenceNumByCode);
                //插入基础人员信息
                int count = personInfoService.insertCerPersonInfo(cerPersonalInfo);
                //添加初始数据信息
                tkmSysteminitImportInfo.setPersonId(cerPersonalInfo.getId());
                tkmSysteminitImportInfo.setScreeningId(cerPersonalInfo.getScreeningId());
                int count2 = systeminitImportInfoService.insertRecord(tkmSysteminitImportInfo);
                return JsonObj.success("添加成功");
            }else {
                //人员信息已经存在，判断该人员是否已经上报过
                int initCountByPersonId = systeminitImportInfoService.findInitCountByPersonId(tkmSysteminitImportInfo.getPersonId());
                if (initCountByPersonId>0){
                    return JsonObj.error("该人员已经进行过数据上报，请直接进行随访");
                }
                int count2 = systeminitImportInfoService.insertRecord(tkmSysteminitImportInfo);
                return JsonObj.success("添加成功");
            }

        }
        return JsonObj.error("信息不全，请检查传参");
    }
    private CerPersonalInfo getCerPersonalInfo(CerInitData each) {
        CerPersonalInfo target = new CerPersonalInfo();
        target.setName(each.getName());
        target.setIdCard(each.getIdCard());
        target.setSex(each.getSex());
        target.setAddr(each.getAddr());
        target.setPhone(each.getPhone());
        target.setBirthday(each.getBirthday());
        target.setCityName(each.getCityName());
        target.setCountyName(each.getCountyName());
        target.setProvinceName(each.getProvinceName());
        target.setDistrictName(each.getDistrictName());
        target.setNationCode(each.getNationCode());
        target.setVillageName(each.getVillageName());
        target.setQfjg(each.getQfjg());
        target.setYxStartDate(each.getYxStartDate());
        target.setYxEndDate(each.getYxEndDate());
        //省市区街道，民族编码
        target.setNationName(each.getNationName());
        target.setProvinceId(each.getProvinceId());
        target.setCityId(each.getCityId());
        target.setDistrictId(each.getDistrictId());
        target.setCountyId(each.getCountyId());
        target.setVillageId(each.getVillageId());
        return target;
    }
    private TkmSysteminitImportInfo getTkmSysteminitImportInfo(CerInitData each) {
        TkmSysteminitImportInfo target = new TkmSysteminitImportInfo();
        target.setName(each.getName());
        target.setSfz(each.getIdCard());
        target.setSex(each.getSex());
        target.setAddr(each.getAddr());
        target.setPhone(each.getPhone());
        target.setCityName(each.getCityName());
        target.setProvinceName(each.getProvinceName());
        target.setDistrictName(each.getDistrictName());
        target.setProvinceId(each.getProvinceId());
        target.setCityId(each.getCityId());
        target.setDistrictId(each.getDistrictId());
        target.setCountyId(each.getCountyId());
        target.setCountyName(each.getCountyName());
        target.setVillageName(each.getVillageName());
        target.setVillageId(each.getVillageId());
        target.setPersonId(each.getPersonId());
        target.setWrittenConsentUrl(each.getWrittenConsentUrl());
        target.setWrittenConsentFilePath(each.getWrittenConsentFilePath());
        target.setSelfSignDate(each.getSelfSignDate());
        target.setProofDate(each.getProofDate());
        target.setProofName(each.getProofName());
        target.setScreeningType(each.getScreeningType());
        target.setScreeningId(each.getScreeningId());
        return target;
    }

    @PostMapping("batchDeletion")
    @ApiOperation("批量删除")
    public JsonObj batchDeletion(@RequestBody PageData pageData) {
        return cerSysteminitImportInfoService.batchDeletion(pageData);
    }

    @PostMapping("oneClickDelete")
    @ApiOperation("一键删除")
    public JsonObj oneClickDelete(@RequestBody PageData pageData) {
        return cerSysteminitImportInfoService.oneClickDelete(pageData);
    }

    @PostMapping("queryAllExportData")
    @ApiOperation("查询待导出的所有数据")
    public JsonObj queryAllExportData(@RequestBody PageData pageData) {
        List<LinkedHashMap<String, Object>> list = cerSysteminitImportInfoService.queryAllExportDataBy(
                pageData);
        Map<String, Object> map = new HashedMap<>();
        map.put("data", list);
        return JsonObj.success(map);
    }

    /**
     * 计划随访添加人员筛选
     */
    @PostMapping("/waitingFollowUpPersonnel")
    public ListResult<Object> waitingFollowUpPersonnel(@RequestBody PageData pageData) {
        return ResultBuilder.buildListSuccess(cerSysteminitImportInfoService.waitingFollowUpPersonnel(pageData));
    }

    /**
     * 数据上报导出
     */
    @PostMapping("/newQueryAllExportData")
    public JsonObj newQueryAllExportData(@RequestBody PageData pageData) {
        List<LinkedHashMap<String,Object>> list  = cerSysteminitImportInfoService.newQueryAllExportData(pageData);
        Map<String,Object> map = new HashMap<>();
        map.put("data",list);
        return JsonObj.success(map);
    }

    /**
     * 删除数据上报
     */
    @GetMapping("/del")
    public JsonObj del(@RequestParam String id) {
        return cerSysteminitImportInfoService.del(id);
    }

    /**
     * 图像上报
     */
    @PostMapping("/imageEscalation")
    public JsonObj imageEscalation(@RequestBody PageData pageData) {
        return cerSysteminitImportInfoService.imageEscalation(pageData);
    }

    @PostMapping(value = "/importGJData")
    @ApiOperation("导入（国家格式）")
    public JsonObj importGJData(@RequestParam("file") MultipartFile file, HttpServletResponse response)
            throws IOException {
        PageData pageData = getPageData();
        String userId = (String) pageData.get("user");
        return cerSysteminitImportInfoService.importGJData(file,response,userId);
    }

    /**
     * 体检表
     */
    @PostMapping("/editPhysicalExaminationInfo")
    public JsonObj editPhysicalExaminationInfo(@RequestBody ZjcodePhysicalExaminationInfo info) {
        return cerSysteminitImportInfoService.editPhysicalExaminationInfo(info);
    }

    /**
     * 根据id查询体检表数据
     */
    @GetMapping("/getPhysicalExaminationByInfoId")
    public JsonObj getPhysicalExaminationByInfoId(@RequestParam String infoId) {
        return cerSysteminitImportInfoService.getPhysicalExaminationByInfoId(infoId);
    }

    /**
     * 数据上报——添加：根据当前登录用户的所在机构，默认渲染省、市的数据
     */
    @GetMapping("/getAreaByUserId")
    public JsonObj getAreaByUserId(@RequestParam Long userId) {
        return cerSysteminitImportInfoService.getAreaByUserId(userId);
    }


    @PostMapping("exportSelfTestTable")
    @ApiOperation("导出自测表信息")
    public void exportSelfTestTable(HttpServletResponse response) {
        PageData pageData = getPageData();
        cerSysteminitImportInfoService.exportSelfTestTable(pageData,response);
    }

    @ApiOperation("上报内镜/病理信息到国家平台")
    @PostMapping("/pushNation")
    public JsonObj pushNation(@RequestBody List<String> ids){
        PageData pageData = getPageData();
        String userId = getLoginUserId(pageData);
        return dataPushNationService.pushNation(ids, userId);
    }
}
